package com.dms.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: JwtToken
 * @package: com.eaby.utils
 * @description  Token生成解析工具类
 * @author: sk
 */
public class JwtToken {

    /**
     * 公用秘钥，保存在服务器中，以防被攻击
     */
    public static String SECRET = "WangNanShu";

    /**
     * 生成Token
     * @return
     * @throws Exception
     */
    public static String createToken(String loginName,String password) throws Exception{
        //签发时间
        Date isDate = new Date();

        //过期时间
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.HOUR, 12);
        Date expiresDate = nowTime.getTime();


        Map<String,Object> map = new HashMap<String, Object>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        String token = JWT.create()
                .withHeader(map) //header
                .withClaim("loginName",loginName) //payload
                .withClaim("password",password)
                .withExpiresAt(expiresDate) //设置过期时间，过期时间要大于签证时间
                .withIssuedAt(isDate) //设置签发时间
                .sign(Algorithm.HMAC256(SECRET)); //加密
        return token;

    }

    /**
     *  解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        }catch (Exception e){
            throw new RuntimeException("登录凭证已过期，请重新登录");
        }
        return jwt.getClaims();
    }

/*    public static void main(String[] args) throws Exception {
        String token = JwtToken.createToken("admin","admin12");
        System.out.println("Token:"+token);
        Map<String,Claim> claims = JwtToken.verifyToken(token);
        System.out.println(claims.get("loginName").asString());
        System.out.println(claims.get("password").asString());

        String tokenEx = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6ImFkbWluMTIiLCJsb2dpbk5hbWUiOiJhZG1pbiIsImV4cCI6MTU5ODI4NzE2NSwiaWF0IjoxNTk4MjQzOTY1fQ.BlPiGIOEogSTYzr7SoJmrcPeJos9iQkbyumKHizby3c";
        Map<String,Claim> cl = JwtToken.verifyToken(tokenEx);
        System.out.println(cl);

    }*/
}
